package com.unifiedlibrary.amall_page.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;

import com.beyondsoft.smarthome.utils.logs.LogTag;
import com.unifiedlibrary.amall_page.BuildConfig;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;


/**
 * Created by Smile on 17/5/10.
 */
public class MainApp extends Application {
    private static final String TAG = "MainClass";
    private static MainApp instance;
    private static final List<Activity> activitys = Collections.synchronizedList(new LinkedList<Activity>());
    private final int CHECK_DELAY = 500;

    //用于判断是否程序在前台
    private boolean foreground = false, paused = true;
    //handler用于处理切换activity时的短暂时期可能出现的判断错误
    private Handler handler = new Handler();
    private Runnable check;

    //static 代码段可以防止内存泄露
//    static {
//        //设置全局的Header构建器
//        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
//            @Override
//            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
//                layout.setPrimaryColorsId(R.color.color_white, R.color.color_black1);//全局设置主题颜色
//                ClassicsHeader header = new ClassicsHeader(context);
//                header.setEnableLastTime(false);
//                return header;//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
//            }
//        });
//        //设置全局的Footer构建器
//        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
//            @Override
//            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
//                //指定为经典Footer，默认是 BallPulseFooter
//                return new ClassicsFooter(context).setDrawableSize(20);
//            }
//        });
//    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
//        MainAppHelper.initBugCrash(this);
        MainAppHelper.initLog();
//        String baseUrl = SharedPreferencesUtil.getInstance().getString(Constant.User.EMPLOYEE_IP);
//        if(TextUtils.isEmpty(baseUrl)){
//            NetConstant.API_BASE_TEST=NetConstant.NetEnvirment.getProdEnvir();
//        }else {
//            NetConstant.API_BASE_TEST=baseUrl;
//        }

        registerActivityListener();

        initCockroach(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
//        LanContextWrapper lanContextWrapper = new LanContextWrapper(instance);
//        lanContextWrapper.saveLanguageBySharedPreferences(instance);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
//        android.support.multidex.MultiDex.install(this);
    }

    public static MainApp getInstance() {
        return instance;
    }

    public boolean isDebug() {
        return BuildConfig.DEBUG;
    }

    public static String getAppVersionName() {
        return BuildConfig.VERSION_NAME;
    }

    public static int getAppVersionCode() {
        return BuildConfig.VERSION_CODE;
    }

    public static String getAppPackageName() {
        return BuildConfig.APPLICATION_ID;
    }

    public void initCockroach(boolean enabled) {
//        if (enabled)
//            Cockroach.install((thread, throwable) -> {
//                try {
//                    System.err.println("at " + thread.getName() + " thread");
//                    System.err.println("Exception: " + throwable.toString());
//                    System.out.println("https://stackoverflow.com/search?q=".concat(throwable.toString()));
//                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//                    throwable.printStackTrace(new PrintStream(outputStream));
//                    String str = outputStream.toString();
//                    System.err.println(str);
//                } catch (Cockroach.QuitCockroachException e) {
//                    e.printStackTrace();
//                }
//            });
//        else Cockroach.uninstall();
    }

//    private void initHttp(Application context) {
//        OkGo.init(context);
//        try {
//            OkGo okGo = OkGo.getInstance();
//            okGo.debug("OkGo", Level.INFO, true)
//                    .setConnectTimeout(OkGo.DEFAULT_MILLISECONDS)  //全局的连接超时时间
//                    .setReadTimeOut(OkGo.DEFAULT_MILLISECONDS)     //全局的读取超时时间
//                    .setWriteTimeOut(OkGo.DEFAULT_MILLISECONDS)    //全局的写入超时时间
//                    .setCacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
//                    .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
//                    //可以全局统一设置超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
//                    .setRetryCount(0)
//                    //可以设置https的证书,以下几种方案根据需要自己设置
//                    .setCertificates();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    /**
     * @param activity 作用说明 ：添加一个activity到管理里
     */
    public void pushActivity(Activity activity) {
        activitys.add(activity);
        LogTag.d(TAG, "activityList:size:" + activitys.size());
    }

    /**
     * @param activity 作用说明 ：删除一个activity在管理里
     */
    public void popActivity(Activity activity) {
        activitys.remove(activity);
        LogTag.d(TAG, "activityList:size:" + activitys.size());
    }


    /**
     * get current Activity 获取当前Activity（栈中最后一个压入的）
     */
    public static Activity currentActivity() {
        if (activitys == null || activitys.isEmpty()) {
            return null;
        }
        Activity activity = activitys.get(activitys.size() - 1);
        return activity;
    }

    /**
     * 结束当前Activity（栈中最后一个压入的）
     */
    public static void finishCurrentActivity() {
        if (activitys == null || activitys.isEmpty()) {
            return;
        }
        Activity activity = activitys.get(activitys.size() - 1);
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public static void finishActivity(Activity activity) {
        if (activitys == null || activitys.isEmpty()) {
            return;
        }
        if (activity != null) {
            activitys.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public static void finishActivity(Class<?> cls) {
        if (activitys == null || activitys.isEmpty()) {
            return;
        }
        for (Activity activity : activitys) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 按照指定类名找到activity
     *
     * @param cls
     * @return
     */
    public static Activity findActivity(Class<?> cls) {
        Activity targetActivity = null;
        if (activitys != null) {
            for (Activity activity : activitys) {
                if (activity.getClass().equals(cls)) {
                    targetActivity = activity;
                    break;
                }
            }
        }
        return targetActivity;
    }

    /**
     * @return 作用说明 ：获取当前最顶部activity的实例
     */
    public Activity getTopActivity() {
        Activity mBaseActivity;
        synchronized (activitys) {
            final int size = activitys.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = activitys.get(size);
        }
        return mBaseActivity;

    }

    /**
     * @return 作用说明 ：获取当前最顶部的acitivity 名字
     */
    public String getTopActivityName() {
        Activity mBaseActivity = null;
        synchronized (activitys) {
            final int size = activitys.size() - 1;
            if (size < 0) {
                return null;
            }
            mBaseActivity = activitys.get(size);
        }
        return mBaseActivity.getClass().getName();
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivity() {
        if (activitys == null) {
            return;
        }
        for (Activity activity : activitys) {
            activity.finish();
        }
        activitys.clear();
//        MainAppHelper.recyclePushServiceAndNotify();
    }
    private int mFinalCount;
    private void registerActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                /**
                 *  监听到 Activity创建事件 将该 Activity 加入list
                 */
                pushActivity(activity);

            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                paused = false;
                foreground = true;

                if (check != null)
                    handler.removeCallbacks(check);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                paused = true;
                if (check != null)
                    handler.removeCallbacks(check);
                handler.postDelayed(check = new Runnable() {
                    @Override
                    public void run() {
                        if (foreground && paused) {
                            foreground = false;
                            LogTag.i(TAG, "went background");
                        } else {
                            LogTag.i(TAG, "still foreground");
                        }
                    }
                }, CHECK_DELAY);

            }

            @Override
            public void onActivityStopped(Activity activity) {
                mFinalCount--;
                //如果mFinalCount ==0，说明是前台到后台
                LogTag.i("onActivityStopped", mFinalCount +"");
                if (mFinalCount == 0){
                    //说明从前台回到了后台
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                if (null == activitys && activitys.isEmpty()) {
                    return;
                }
                if (activitys.contains(activity)) {
                    /**
                     *  监听到 Activity销毁事件 将该Activity 从list中移除
                     */
                    popActivity(activity);
                }
            }
        });
    }

    public boolean isForeground() {
        return foreground;
    }

}